#!/bin/bash
# this is the functions file for the dhcpd-plugin
#
# openQRM Enterprise developed by openQRM Enterprise GmbH.
#
# All source code and content (c) Copyright 2014, openQRM Enterprise GmbH unless specifically noted otherwise.
#
# This source code is released under the GNU General Public License version 2, unless otherwise agreed with openQRM Enterprise GmbH.
# The latest version of this license can be found here: src/doc/LICENSE.txt
#
# By using this software, you acknowledge having read this license and agree to be bound thereby.
#
#           http://openqrm-enterprise.com
#
# Copyright 2014, openQRM Enterprise GmbH <info@openqrm-enterprise.com>
#

OPENQRM_SERVER_DEFAULT_DOMAIN="openqrm"
OPENQRM_PLUGIN_DHCPD_CONF_TEMPLATE="$OPENQRM_SERVER_BASE_DIR/openqrm/plugins/dhcpd/etc/templates/openqrm-plugin-dhcpd-configuration.template"
OPENQRM_PLUGIN_DHCPD_CONF="$OPENQRM_SERVER_BASE_DIR/openqrm/plugins/dhcpd/etc/dhcpd.conf"
OPENQRM_PLUGIN_DHCPD_NETWORK_TEMPLATE="$OPENQRM_SERVER_BASE_DIR/openqrm/plugins/dhcpd/etc/templates/openqrm-plugin-dhcpd-network.template"
OPENQRM_PLUGIN_DHCPD_LEASE_DIR="$OPENQRM_SERVER_BASE_DIR/openqrm/plugins/dhcpd/var/state/dhcp"

# logs for dhcpd
function dhcpd_log() {
	local COMPONENT=$1
	shift
	local MESSAGE=$@
	logger -i -t "dhcpd plug-in" "$COMPONENT : $MESSAGE"
}


#
# $1:  ip address
# $2:  subnet mask
# $3: [first/last/net] or  $3 [next] [offset]
# out: net, first-ip, last-ip or next-ip
#
function openqrm_plugin_dhcpd_range_calculator() {
        perl - $1 $2 $3 $4<<'EOF'
ipp($ARGV[0],$ARGV[1])."\n";

sub ipp
{

my $ipaddr=$ARGV[0];
my $nmask=$ARGV[1];
my $type=$ARGV[2];
my $offset=$ARGV[3];

my @addrarr=split(/\./,$ipaddr);
my ( $ipaddress ) = unpack( "N", pack( "C4",@addrarr ) );

my @maskarr=split(/\./,$nmask);
my ( $netmask ) = unpack( "N", pack( "C4",@maskarr ) );

my $netadd = ( $ipaddress & $netmask );
my @netarr=unpack( "C4", pack( "N",$netadd ) );
my $netaddress=join(".",@netarr);

if ($type eq 'last') {
        my $bcast = ( $ipaddress & $netmask ) + ( ~ $netmask ) -1;
        my @bcastarr=unpack( "C4", pack( "N",$bcast ) ) ;
        my $lastaddress=join(".",@bcastarr);
        print "$lastaddress \n";
} elsif ($type eq 'net') {
        my $netadd = ( $ipaddress & $netmask );
        my @netarr=unpack( "C4", pack( "N",$netadd ) );
        my $netaddress=join(".",@netarr);
        print "$netaddress\n";
} elsif ($type eq 'next') {

        my $bcast = ( $ipaddress & $netmask ) + ( ~ $netmask ) -1 - $offset;
        my @bcastarr=unpack( "C4", pack( "N",$bcast ) ) ;
        my $nextaddress=join(".",@bcastarr);
        print "$nextaddress\n";
} else {
        my $firstadd = ( $ipaddress & $netmask ) + 1;
        my @netarr=unpack( "C4", pack( "N",$firstadd ) );
        my $firstaddress=join(".",@netarr);
        print "$firstaddress\n";
}
}
EOF
}


